import { Card, Typography, Button, Progress, Tag, Table, Space, Tabs, Row, Col, Statistic, Input, Form, Select, Modal, message, Spin, Descriptions, Divider, Upload, Popconfirm, Dropdown, Menu } from '@/utils/antd-imports';
import { EditOutlined, DeleteOutlined, CheckOutlined, CloseOutlined, FileDoneOutlined, FileAddOutlined, PartitionOutlined, TransactionOutlined, AlertOutlined, PieChartOutlined, PlusOutlined, SearchOutlined, TeamOutlined, DollarOutlined, UploadOutlined, FileExcelOutlined, DownloadOutlined, MenuOutlined, EyeOutlined } from '@/utils/icons';
import React, { useState, useEffect } from 'react';
import { projectApi } from '@/api/projectApi';
import { projectAcceptanceApi, acceptanceMemberApi } from '@/api/projectAcceptanceApi';
import { dynamicImportApi } from '@/api/dynamicImportApi';
import { exportToExcel } from '@/utils/excelExport';
import employeeApi from '@/api/employeeApi';
import moment from 'moment';














import DatePicker from 'antd/es/date-picker';
import InputNumber from 'antd/es/input-number';

// 单价类型选项
const priceTypes = [
  { value: 'hour', label: '时' },
  { value: 'day', label: '日' },
  { value: 'month', label: '月' }
];

import Grid from 'antd/es/grid';

import { SubcontractTab } from './Project-Detail/SubcontractTab';
import { SettlementTab } from './Project-Detail/SettlementTab';
import { RiskTab } from './Project-Detail/RiskTab';
import { StatisticsTab } from './Project-Detail/StatisticsTab';
import { OutputValueTab } from './Project-Detail/OutputValueTab';
import MembersTab from './Project-Detail/MembersTab';

const { Title, Text } = Typography;
const { TabPane } = Tabs;
const { Option } = Select;
const { useBreakpoint } = Grid;

const SubProjectTable = ({ projectId, projectCode, projectName, onProjectSelect }) => {
  const screens = useBreakpoint();
  
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [subProjectsData, setSubProjectsData] = useState([]);
  const [subcontractProjectsData, setSubcontractProjectsData] = useState([]);
  const [acceptanceList, setAcceptanceList] = useState([]);
  const [activeTab, setActiveTab] = useState('all'); // 新增：当前激活的tab

  // 表单实例
  const [form] = Form.useForm();
  const [contractModalVisible, setContractModalVisible] = React.useState(false);
  const [currentContract, setCurrentContract] = React.useState(null);
  
  // 验收相关状态
  const [acceptanceVisible, setAcceptanceVisible] = useState(false);
  const [acceptanceMembers, setAcceptanceMembers] = useState([]);
  const [loadingMembers, setLoadingMembers] = useState(false);
  const [currentAcceptanceRecord, setCurrentAcceptanceRecord] = useState(null);
  
  // 添加成员相关状态
  const [addMemberVisible, setAddMemberVisible] = useState(false);
  const [memberForm] = Form.useForm();
  
  // 批量导入相关状态
  const [batchImportVisible, setBatchImportVisible] = useState(false);
  const [importLoading, setImportLoading] = useState(false);

  // 处理添加项目按钮点击
  const handleAddProject = () => {
    if (onProjectSelect) {
      onProjectSelect({
        type: 'create',
        projectCode: projectCode
      });
    }
  };

  // 处理批量导入按钮点击
  const handleBatchImport = () => {
    setBatchImportVisible(true);
  };

  // 处理上传Excel文件
  const handleExcelUpload = async (file) => {
    setImportLoading(true);
    try {
      const response = await dynamicImportApi.importProject(file);
      
      if (response.code === 200) {
        message.success('批量导入成功');
        setBatchImportVisible(false);
        // 重新加载数据
        loadSubProjects();
      } else {
        message.error(response.message || '批量导入失败');
      }
    } catch (error) {
      console.error('批量导入失败:', error);
      message.error('批量导入失败');
    } finally {
      setImportLoading(false);
    }
    return false; // 阻止默认上传行为
  };

  // 处理作废项目
  const handleVoidProject = async (subProjectId) => {
    try {
      const response = await projectApi.voidProject(subProjectId);
      if (response.code === 200) {
        message.success('项目已作废');
        loadSubProjects();
      } else {
        message.error(response.message || '作废失败');
      }
    } catch (error) {
      console.error('作废项目失败:', error);
      message.error('作废项目失败');
    }
  };

  // 处理编辑子项目
  const handleEditSubProject = (subProjectId) => {
    if (onProjectSelect) {
      const subProject = subProjectsData.find(p => p.id === subProjectId);
      onProjectSelect({
        type: 'project-edit',
        projectId: subProjectId,
        projectCode: projectCode,
        subProjectName: subProject?.projectSubname
      });
    }
  };

  // 处理筛选表单提交
  const handleSearch = (values) => {
    console.log('筛选条件:', values);
    // 这里可以添加筛选逻辑
  };

  // 重置筛选表单
  const handleReset = () => {
    form.resetFields();
  };

  // 显示合同详情
  const showContractDetail = (contractNo) => {
    setCurrentContract({
      no: contractNo,
      content: `这是合同${contractNo}的详细内容...`
    });
    setContractModalVisible(true);
  };

  // 根据状态获取标签颜色
  const getStatusColor = (status) => {
    const colors = {
      '未验收': 'default',
      '验收中': 'blue',
      '开票中': 'orange',
      '待回款': 'purple',
      '已回款': 'green',
      '待验收': 'default',
      '已验收': 'green',
      '验收失败': 'red'
    };
    return colors[status] || 'default';
  };

  // 处理验收按钮点击
  const handleAcceptance = async (record) => {
    setCurrentAcceptanceRecord(record);
    setAcceptanceVisible(true);
    
    // 加载验收成员数据
    if (record.id) {
      setLoadingMembers(true);
      try {
        const response = await projectAcceptanceApi.getMembersByAcceptance(record.id);
        if (response.code === 200) {
          setAcceptanceMembers(response.data || []);
        } else {
          message.error('加载验收成员失败');
        }
      } catch (error) {
        console.error('加载验收成员失败:', error);
        message.error('加载验收成员失败');
      } finally {
        setLoadingMembers(false);
      }
    }
  };

  // 添加验收成员
  const handleAddMember = () => {
    setAddMemberVisible(true);
    memberForm.resetFields();
  };

  // 确认添加成员
  const handleConfirmAddMember = async () => {
    try {
      const values = await memberForm.validateFields();
      
      const newMember = {
        id: Date.now(), // 临时ID
        employeeName: '',
        employeeCode: '',
        jobTitle: values.position,
        unitPrice: values.price,
        priceType: values.priceType,
        actualHours: 0, // 初始化为0，后续可以在列表中选择员工后填入
        settlementAmount: 0,
        acceptanceId: currentAcceptanceRecord?.id
      };
      
      setAcceptanceMembers(prev => [...prev, newMember]);
      setAddMemberVisible(false);
      memberForm.resetFields();
      message.success('添加成员成功');
    } catch (error) {
      console.error('添加成员失败:', error);
    }
  };

  // 加载子项目数据
  const loadSubProjects = async () => {
    if (!projectCode) return;
    
    setLoading(true);
    try {
      const response = await projectApi.getSubProjectsByProjectCode(projectCode);
      if (response.code === 200) {
        // 后端已经返回了 customerName, contractCompanyName, managerName, directorName 等字段
        // 直接使用返回的数据，不需要额外的数据增强
        setSubProjectsData(response.data || []);
      } else {
        message.error(response.message || '加载子项目数据失败');
      }
    } catch (error) {
      console.error('加载子项目数据失败:', error);
      message.error('加载子项目数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载验收单数据
  const loadAcceptanceList = async () => {
    if (!projectCode) return;
    
    try {
      const response = await projectApi.getAcceptancesByProjectCode(projectCode);
      if (response.code === 200) {
        setAcceptanceList(response.data || []);
      } else {
        message.error(response.message || '加载验收单数据失败');
      }
    } catch (error) {
      console.error('加载验收单数据失败:', error);
      message.error('加载验收单数据失败');
    }
  };

  // 加载分包项目数据
  const loadSubcontractProjects = async () => {
    if (!projectCode) return;
    
    try {
      const response = await projectApi.getSubcontractProjectsByProjectCode(projectCode);
      if (response.code === 200) {
        // 后端已经返回了名称字段，直接使用
        setSubcontractProjectsData(response.data || []);
      } else {
        message.error(response.message || '加载分包项目数据失败');
      }
    } catch (error) {
      console.error('加载分包项目数据失败:', error);
      message.error('加载分包项目数据失败');
    }
  };

  // 组件挂载时加载数据
  useEffect(() => {
    loadSubProjects();
    loadAcceptanceList();
    loadSubcontractProjects();
  }, [projectCode]);

  // 子项目表格列定义（更新字段名）
  const subProjectColumns = [
    {
      title: '子项目名称',
      dataIndex: 'projectSubname',
      key: 'projectSubname',
      width: 200,
      fixed: 'left',
      render: (text) => <Text strong>{text || '-'}</Text>
    },
    {
      title: '客户',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 150,
      render: (text) => <Text>{text || '未分配'}</Text>
    },
    {
      title: '项目类型',
      dataIndex: 'projectType',
      key: 'projectType',
      width: 120,
      render: (type) => {
        const typeMap = {
          '1': '人力项目',
          '2': '整包项目', 
          '3': '分包项目',
          'manpower': '人力项目',
          'turnkey': '整包项目',
          'subcontract': '分包项目'
        };
        const typeName = typeMap[type] || type;
        const color = typeName === '整包项目' ? 'geekblue' : 'cyan';
        return <Tag color={color}>{typeName}</Tag>;
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status) => (
        <Tag color={getStatusColor(status)}>{status}</Tag>
      )
    },
    {
      title: '签约公司',
      dataIndex: 'contractCompanyName',
      key: 'contractCompanyName',
      width: 150,
      render: (text) => <Text>{text || '未分配'}</Text>
    },
    {
      title: '项目经理',
      dataIndex: 'managerName',
      key: 'managerName',
      width: 120,
      render: (text) => <Text>{text || '未分配'}</Text>
    },
    {
      title: '项目总监',
      dataIndex: 'directorName',
      key: 'directorName',
      width: 120,
      render: (text) => <Text>{text || '未分配'}</Text>
    },
    {
      title: '预算金额(元)',
      dataIndex: 'projectBudget',
      key: 'projectBudget',
      width: 150,
      render: (amount) => amount ? `¥${amount.toLocaleString()}` : '-'
    },
    {
      title: '实际金额(元)',
      dataIndex: 'actualAmount',
      key: 'actualAmount',
      width: 150,
      render: (amount) => amount ? `¥${(amount / 10000).toFixed(2)}万` : '-'
    },
    {
      title: '开始日期',
      dataIndex: 'startDate',
      key: 'startDate',
      width: 120
    },
    {
      title: '结束日期',
      dataIndex: 'endDate',
      key: 'endDate',
      width: 120
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="text" 
            icon={<EditOutlined />} 
            onClick={() => handleEditSubProject(record.id)}
          />
          <Popconfirm
            title="确认作废"
            description="确定要作废该项目吗？作废后，该项目及其关联的验收单和验收成员都将被标记为作废状态。"
            onConfirm={() => handleVoidProject(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <Button 
              type="text" 
              danger 
              icon={<CloseOutlined />}
            >
              作废
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 验收单表格列定义（用于结算tab）
  const acceptanceColumns = [
    {
      title: '验收单号',
      dataIndex: 'acceptanceNo',
      key: 'acceptanceNo',
      width: 180,
      fixed: 'left',
    },
    {
      title: '子项目名称',
      dataIndex: 'subProjectName',
      key: 'subProjectName',
      width: 200
    },
    {
      title: '客户',
      dataIndex: 'client',
      key: 'client',
      width: 150
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      width: 120
    },
    {
      title: '科室',
      dataIndex: 'section',
      key: 'section',
      width: 120
    },
    {
      title: '合同号',
      dataIndex: 'contractNo',
      key: 'contractNo',
      width: 150
    },
    {
      title: '验收日期',
      dataIndex: 'acceptanceDate',
      key: 'acceptanceDate',
      width: 120,
      render: (date) => date ? (typeof date === 'string' ? date.split('T')[0] : date) : '-'
    },
    {
      title: '开始时间',
      dataIndex: 'startDate',
      key: 'startDate',
      width: 120,
      render: (date) => date ? (typeof date === 'string' ? date.split('T')[0] : date) : '-'
    },
    {
      title: '结束时间',
      dataIndex: 'endDate',
      key: 'endDate',
      width: 120,
      render: (date) => date ? (typeof date === 'string' ? date.split('T')[0] : date) : '-'
    },
    {
      title: '工时',
      key: 'workHours',
      width: 150,
      render: (_, record) => {
        const workTypeMap = {
          'hour': '时',
          'day': '天',
          'month': '月'
        };
        const workTypeName = workTypeMap[record.workType] || record.workType || '时';
        // 如果验收单有成员列表且成员有工时数据，则计算总工时
        if (record.members && record.members.length > 0) {
          const totalHours = record.members.reduce((sum, member) => {
            return sum + (member.actualHours || member.estimatedHours || 0);
          }, 0);
          return <Text strong>{totalHours.toFixed(2)} {workTypeName}</Text>;
        }
        return <Text type="secondary">-</Text>;
      }
    },
    {
      title: '已验收时间',
      dataIndex: 'acceptanceCompletionTime',
      key: 'acceptanceCompletionTime',
      width: 150,
      render: (time) => {
        if (!time) return '-';
        const date = new Date(time);
        return date.toLocaleString('zh-CN', { 
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
      }
    },
    {
      title: '预算金额',
      dataIndex: 'budgetAmount',
      key: 'budgetAmount',
      width: 120,
      render: (amount) => amount ? `¥${amount.toLocaleString()}` : '-'
    },
    {
      title: '验收金额',
      dataIndex: 'acceptanceAmount',
      key: 'acceptanceAmount',
      width: 120,
      render: (amount) => amount ? `¥${amount.toLocaleString()}` : '-'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={getStatusColor(status)}>{status}</Tag>
      )
    },
    {
      title: '对接人',
      dataIndex: 'contactPerson',
      key: 'contactPerson',
      width: 120
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          {record.status === '待验收' ? (
            <a onClick={() => handleAcceptance(record)}>验收</a>
          ) : record.status === '已验收' ? (
            <a onClick={() => handleAcceptance(record)}>详情</a>
          ) : null}
        </Space>
      )
    }
  ];

  // 计算立项页签的统计数据
  const calculateApprovalStats = (data = subProjectsData) => {
    const total = data.length;
    const paid = data.filter(p => p.status === '已回款').length;
    const waitingPayment = data.filter(p => p.status === '待回款').length;
    const invoicing = data.filter(p => p.status === '开票中').length;
    const totalBudget = data.reduce((sum, p) => sum + (p.projectBudget || 0), 0);
    
    return {
      total,
      paid,
      waitingPayment,
      invoicing,
      totalBudget,
      avgCostRate: 0.85, // 默认值，如果后端有该字段再更新
      totalManHours: 0, // 默认值，如果后端有该字段再更新
      avgHourlyRate: 0 // 默认值，如果后端有该字段再更新
    };
  };

  // 根据当前激活的tab筛选数据
  const getFilteredSubProjects = () => {
    // 首先排除分包项目类型（projectType === '3'）
    const nonSubcontractData = subProjectsData.filter(p => p.projectType !== '3');
    
    switch (activeTab) {
      case 'turnkey':
        return nonSubcontractData.filter(p => p.projectType === '2');
      case 'manpower':
        return nonSubcontractData.filter(p => p.projectType === '1');
      case 'subcontract':
        return subProjectsData.filter(p => p.projectType === '3');
      default:
        return nonSubcontractData;
    }
  };

  const filteredSubProjects = getFilteredSubProjects();
  const approvalStats = calculateApprovalStats(filteredSubProjects);

  // 处理tab切换
  const handleTabChange = (key) => {
    setActiveTab(key);
  };

  // 导出立项数据
  const handleExportProjects = () => {
    const dataToExport = getFilteredSubProjects();
    if (!dataToExport || dataToExport.length === 0) {
      message.warning('没有数据可导出');
      return;
    }
    
    try {
      const filename = `立项数据_${new Date().getTime()}.xlsx`;
      exportToExcel(dataToExport, subProjectColumns, filename);
      message.success('立项数据导出成功');
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败，请重试');
    }
  };

  return (
    <>
      <div style={{ padding: '24px 24px' }}>
        <Title level={3} style={{ margin: 0 }}>
          项目详情 - {projectName || projectCode || '未指定项目'}
        </Title>
      </div>

      <Spin spinning={loading}>
        <Card bordered={false}>
          <Tabs defaultActiveKey="1" type="card" onChange={handleTabChange}>
            <TabPane
              tab={
                <span>
                  <FileAddOutlined />
                  立项
                </span>
              }
              key="1"
            >
              
              <div style={{ overflowX: 'auto', marginBottom: 24 }}>
                <div style={{ display: 'flex', minWidth: 'max-content' }}>
                  <div style={{ minWidth: '150px', marginRight: 16 }}>
                    <Card size="small" style={{ textAlign: 'center' }}>
                      <Statistic
                        title="子项目总数"
                        value={approvalStats.total}
                        precision={0}
                        valueStyle={{ color: '#667eea', fontSize: '24px', fontWeight: 'bold' }}
                      />
                    </Card>
                  </div>
                  <div style={{ minWidth: '150px', marginRight: 16 }}>
                    <Card size="small" style={{ textAlign: 'center' }}>
                      <Statistic
                        title="已回款"
                        value={approvalStats.paid}
                        precision={0}
                        valueStyle={{ color: '#11998e', fontSize: '24px', fontWeight: 'bold' }}
                      />
                    </Card>
                  </div>
                  <div style={{ minWidth: '150px', marginRight: 16 }}>
                    <Card size="small" style={{ textAlign: 'center' }}>
                      <Statistic
                        title="待回款"
                        value={approvalStats.waitingPayment}
                        precision={0}
                        valueStyle={{ color: '#fa709a', fontSize: '24px', fontWeight: 'bold' }}
                      />
                    </Card>
                  </div>
                  <div style={{ minWidth: '150px', marginRight: 16 }}>
                    <Card size="small" style={{ textAlign: 'center' }}>
                      <Statistic
                        title="开票中"
                        value={approvalStats.invoicing}
                        precision={0}
                        valueStyle={{ color: '#f093fb', fontSize: '24px', fontWeight: 'bold' }}
                      />
                    </Card>
                  </div>
                  <div style={{ minWidth: '180px', marginRight: 16 }}>
                    <Card size="small" style={{ textAlign: 'center' }}>
                      <Statistic
                        title="总预算(元)"
                        value={approvalStats.totalBudget}
                        precision={0}
                        valueStyle={{ color: '#4facfe', fontSize: '24px', fontWeight: 'bold' }}
                      />
                    </Card>
                  </div>
                  <div style={{ minWidth: '150px', marginRight: 16 }}>
                    <Card size="small" style={{ textAlign: 'center' }}>
                      <Statistic
                        title="平均成本率"
                        value={approvalStats.avgCostRate * 100}
                        precision={2}
                        suffix="%"
                        valueStyle={{ color: '#43e97b', fontSize: '24px', fontWeight: 'bold' }}
                      />
                    </Card>
                  </div>
                  <div style={{ minWidth: '150px', marginRight: 16 }}>
                    <Card size="small" style={{ textAlign: 'center' }}>
                      <Statistic
                        title="总工时(h)"
                        value={approvalStats.totalManHours}
                        precision={0}
                        valueStyle={{ color: '#fa709a', fontSize: '24px', fontWeight: 'bold' }}
                      />
                    </Card>
                  </div>
                  <div style={{ minWidth: '180px' }}>
                    <Card size="small" style={{ textAlign: 'center' }}>
                      <Statistic
                        title="平均时价(元/h)"
                        value={approvalStats.avgHourlyRate}
                        precision={0}
                        valueStyle={{ color: '#30cfd0', fontSize: '24px', fontWeight: 'bold' }}
                      />
                    </Card>
                  </div>
                </div>
              </div>
              
              {/* 重新设计的筛选表单 */}
              <Card style={{ marginBottom: 16 }}>
                <Form
                  form={form}
                  layout={screens.md ? 'inline' : 'vertical'}
                  onFinish={handleSearch}
                >
                  <Row gutter={[16, 16]} style={{ width: '100%' }}>
                    <Col xs={24} sm={12} md={8} lg={6}>
                      <Form.Item name="name" label="项目名称">
                        <Input placeholder="请输入项目名称" />
                      </Form.Item>
                    </Col>
                    <Col xs={24} sm={12} md={8} lg={6}>
                      <Form.Item name="department" label="部门">
                        <Input placeholder="请输入部门" />
                      </Form.Item>
                    </Col>
                    <Col xs={24} sm={12} md={8} lg={6}>
                      <Form.Item name="team" label="科室">
                        <Input placeholder="请输入科室" />
                      </Form.Item>
                    </Col>
                    <Col xs={24} sm={12} md={8} lg={6}>
                      <Form.Item name="projectType" label="项目类型">
                        <Select placeholder="请选择项目类型" style={{ width: '100%' }}>
                          <Option value="1">人力项目</Option>
                          <Option value="2">整包项目</Option>
                        </Select>
                      </Form.Item>
                    </Col>
                    <Col xs={24} sm={12} md={8} lg={6}>
                      <Form.Item name="status" label="状态">
                        <Select placeholder="请选择状态" style={{ width: '100%' }}>
                          <Option value="未验收">未验收</Option>
                          <Option value="验收中">验收中</Option>
                          <Option value="已验收">已验收</Option>
                          <Option value="开票中">开票中</Option>
                          <Option value="待回款">待回款</Option>
                          <Option value="已回款">已回款</Option>
                          <Option value="验收失败">验收失败</Option>
                        </Select>
                      </Form.Item>
                    </Col>
                    <Col xs={24} style={{ textAlign: 'right' }}>
                      <Space>
                        <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                          搜索
                        </Button>
                        <Button icon={<CloseOutlined />} onClick={handleReset}>
                          重置
                        </Button>
                        <Dropdown
                          overlay={
                            <Menu>
                              <Menu.Item key="add" icon={<PlusOutlined />} onClick={handleAddProject}>
                                添加项目
                              </Menu.Item>
                              <Menu.Item key="batch" icon={<UploadOutlined />} onClick={handleBatchImport}>
                                批量添加
                              </Menu.Item>
                              <Menu.Item key="export" icon={<DownloadOutlined />} onClick={handleExportProjects}>
                                导出数据
                              </Menu.Item>
                            </Menu>
                          }
                          placement="bottomRight"
                        >
                          <Button 
                            type="primary"
                            icon={<MenuOutlined />}
                          >
                            管理
                          </Button>
                        </Dropdown>
                      </Space>
                    </Col>
                  </Row>
                </Form>
              </Card>
                            {/* 立项tab下的子tab - 移到统计卡片上面 */}
              <Tabs defaultActiveKey="all" type="line" onChange={setActiveTab} style={{ marginBottom: 24 }}>
                <TabPane tab="全部" key="all" />
                <TabPane tab="整包" key="turnkey" />
                <TabPane tab="人力" key="manpower" />
              </Tabs>
              <Table
                columns={subProjectColumns}
                dataSource={filteredSubProjects}
                rowKey="id"
                pagination={{ pageSize: 10 }}
                scroll={{ x: 1500 }}
                bordered
                size="middle"
              />
            </TabPane>
            <TabPane
              tab={
                <span>
                  <PartitionOutlined />
                  分包
                </span>
              }
              key="3"
            >
              <SubcontractTab subProjectsData={subcontractProjectsData} />
            </TabPane>
            <TabPane
              tab={
                <span>
                  <TransactionOutlined />
                  结算
                </span>
              }
              key="4"
            >
              {/* 结算统计指标 */}
              <div style={{ overflowX: 'auto', marginBottom: 24 }}>
                <div style={{ display: 'flex', minWidth: 'max-content' }}>
                  <div style={{ minWidth: '150px', marginRight: 16 }}>
                    <Card size="small" style={{ textAlign: 'center' }}>
                      <Statistic
                        title="验收单总数"
                        value={acceptanceList.length}
                        precision={0}
                        valueStyle={{ fontSize: '24px', fontWeight: 'bold' }}
                      />
                    </Card>
                  </div>
                  <div style={{ minWidth: '150px', marginRight: 16 }}>
                    <Card size="small" style={{ textAlign: 'center' }}>
                      <Statistic
                        title="已验收"
                        value={acceptanceList.filter(a => a.status === '已验收').length}
                        precision={0}
                        valueStyle={{ color: '#52c41a', fontSize: '24px', fontWeight: 'bold' }}
                      />
                    </Card>
                  </div>
                  <div style={{ minWidth: '150px', marginRight: 16 }}>
                    <Card size="small" style={{ textAlign: 'center' }}>
                      <Statistic
                        title="验收中"
                        value={acceptanceList.filter(a => a.status === '验收中').length}
                        precision={0}
                        valueStyle={{ color: '#1890ff', fontSize: '24px', fontWeight: 'bold' }}
                      />
                    </Card>
                  </div>
                  <div style={{ minWidth: '150px', marginRight: 16 }}>
                    <Card size="small" style={{ textAlign: 'center' }}>
                      <Statistic
                        title="待验收"
                        value={acceptanceList.filter(a => a.status === '待验收').length}
                        precision={0}
                        valueStyle={{ color: '#faad14', fontSize: '24px', fontWeight: 'bold' }}
                      />
                    </Card>
                  </div>
                  <div style={{ minWidth: '180px', marginRight: 16 }}>
                    <Card size="small" style={{ textAlign: 'center' }}>
                      <Statistic
                        title="总预算金额"
                        value={acceptanceList.reduce((sum, a) => sum + (a.budgetAmount || 0), 0)}
                        precision={0}
                        prefix="¥"
                        valueStyle={{ color: '#722ed1', fontSize: '24px', fontWeight: 'bold' }}
                      />
                    </Card>
                  </div>
                  <div style={{ minWidth: '180px' }}>
                    <Card size="small" style={{ textAlign: 'center' }}>
                      <Statistic
                        title="总验收金额"
                        value={acceptanceList.reduce((sum, a) => sum + (a.acceptanceAmount || 0), 0)}
                        precision={0}
                        prefix="¥"
                        valueStyle={{ color: '#f093fb', fontSize: '24px', fontWeight: 'bold' }}
                      />
                    </Card>
                  </div>
                </div>
              </div>

              {/* 结算筛选表单 */}
              <Card style={{ marginBottom: 16 }}>
                <Form layout="inline">
                  <Form.Item name="status" label="验收状态">
                    <Select placeholder="请选择状态" style={{ width: 150 }}>
                      <Option value="">全部</Option>
                      <Option value="待验收">待验收</Option>
                      <Option value="验收中">验收中</Option>
                      <Option value="已验收">已验收</Option>
                      <Option value="验收失败">验收失败</Option>
                    </Select>
                  </Form.Item>
                  <Form.Item name="dateRange" label="验收日期">
                    <DatePicker.RangePicker style={{ width: 240 }} />
                  </Form.Item>
                  <Form.Item>
                    <Button type="primary" icon={<SearchOutlined />}>
                      搜索
                    </Button>
                  </Form.Item>
                  <Form.Item>
                    <Button icon={<CloseOutlined />}>
                      重置
                    </Button>
                  </Form.Item>
                </Form>
              </Card>

              <Table
                columns={acceptanceColumns}
                dataSource={acceptanceList}
                rowKey="id"
                pagination={{ pageSize: 10 }}
                scroll={{ x: 1500 }}
                bordered
                size="middle"
              />
            </TabPane>
            <TabPane
              tab={
                <span>
                  <DollarOutlined />
                  产值
                </span>
              }
              key="5"
            >
              <OutputValueTab subProjectsData={subProjectsData} />
            </TabPane>
            <TabPane
              tab={
                <span>
                  <AlertOutlined />
                  风险
                </span>
              }
              key="6"
            >
              <RiskTab subProjectsData={subProjectsData} />
            </TabPane>
            <TabPane
              tab={
                <span>
                  <PieChartOutlined />
                  统计
                </span>
              }
              key="7"
            >
              <StatisticsTab subProjectsData={subProjectsData} />
            </TabPane>
          </Tabs>
        </Card>
      </Spin>

      {/* 合同详情弹窗 */}
      <Modal
        title={`合同详情 - ${currentContract?.no}`}
        visible={contractModalVisible}
        onCancel={() => setContractModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setContractModalVisible(false)}>
            关闭
          </Button>
        ]}
      >
        <p>{currentContract?.content}</p>
        <p>合同金额: ¥50,000</p>
        <p>签订日期: 2025-09-01</p>
        <p>合同状态: 已生效</p>
        <p>负责人: 张三</p>
      </Modal>

      {/* 验收模态框 */}
      <Modal
        title={currentAcceptanceRecord?.status === '已验收' ? "项目验收详情" : "项目验收"}
        visible={acceptanceVisible}
        onCancel={() => {
          setAcceptanceVisible(false);
          setAcceptanceMembers([]);
          setCurrentAcceptanceRecord(null);
        }}
        footer={[
          <Button key="cancel" onClick={() => {
            setAcceptanceVisible(false);
            setAcceptanceMembers([]);
            setCurrentAcceptanceRecord(null);
          }}>
            关闭
          </Button>,
          currentAcceptanceRecord?.status !== '已验收' && (
            <Button key="submit" type="primary">
              提交验收
            </Button>
          )
        ].filter(Boolean)}
        width={800}
      >
        <Descriptions bordered column={2} style={{ marginBottom: 16 }}>
          <Descriptions.Item label="验收单号">{currentAcceptanceRecord?.acceptanceNo}</Descriptions.Item>
          <Descriptions.Item label="子项目名称">{currentAcceptanceRecord?.subProjectName}</Descriptions.Item>
          <Descriptions.Item label="客户">{currentAcceptanceRecord?.client}</Descriptions.Item>
          <Descriptions.Item label="部门">{currentAcceptanceRecord?.department}</Descriptions.Item>
          <Descriptions.Item label="科室">{currentAcceptanceRecord?.section}</Descriptions.Item>
          <Descriptions.Item label="预算金额">
            <Text strong>¥{currentAcceptanceRecord?.budgetAmount?.toLocaleString()}</Text>
          </Descriptions.Item>
        </Descriptions>

        <Divider>
          验收成员列表
          {currentAcceptanceRecord?.status !== '已验收' && (
            <Button 
              type="primary" 
              icon={<PlusOutlined />} 
              size="small" 
              style={{ marginLeft: 16 }}
              onClick={handleAddMember}
            >
              添加成员
            </Button>
          )}
        </Divider>

        <Spin spinning={loadingMembers}>
          <Table
            columns={[
              {
                title: '员工姓名',
                dataIndex: 'employeeName',
                key: 'employeeName'
              },
              {
                title: '员工编号',
                dataIndex: 'employeeCode',
                key: 'employeeCode'
              },
              {
                title: '职位',
                dataIndex: 'jobTitle',
                key: 'jobTitle'
              },
              {
                title: '单价',
                dataIndex: 'unitPrice',
                key: 'unitPrice',
                render: (price) => `¥${price?.toLocaleString() || '-'}`
              },
              {
                title: '单价类型',
                dataIndex: 'priceType',
                key: 'priceType'
              },
              {
                title: '实际工时',
                dataIndex: 'actualHours',
                key: 'actualHours'
              },
              {
                title: '结算金额',
                dataIndex: 'settlementAmount',
                key: 'settlementAmount',
                render: (amount) => <Text strong>¥{amount?.toLocaleString() || '-'}</Text>
              }
            ]}
            dataSource={acceptanceMembers}
            rowKey="id"
            pagination={{ pageSize: 5 }}
            bordered
          />
        </Spin>
      </Modal>

      {/* 添加成员弹窗 */}
      <Modal
        title="添加验收成员"
        visible={addMemberVisible}
        onCancel={() => {
          setAddMemberVisible(false);
          memberForm.resetFields();
        }}
        onOk={handleConfirmAddMember}
        okText="确认添加"
        cancelText="取消"
        width={600}
      >
        <Form
          form={memberForm}
          layout="vertical"
        >
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item
                name="position"
                label="岗位名称"
                rules={[{ required: true, message: '请输入岗位名称' }]}
              >
                <Input placeholder="请输入岗位名称" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="price"
                label="单价(元)"
                rules={[{ required: true, message: '请输入单价' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  min={0}
                  precision={2}
                  placeholder="请输入单价"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="priceType"
                label="单价类型"
                rules={[{ required: true, message: '请选择单价类型' }]}
              >
                <Select placeholder="请选择单价类型">
                  {priceTypes.map(type => (
                    <Option key={type.value} value={type.value}>
                      {type.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="contactPerson"
            label="对接人"
          >
            <Input placeholder="请输入对接人姓名" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 批量导入对话框 */}
      <Modal
        title="批量导入项目"
        visible={batchImportVisible}
        onCancel={() => {
          setBatchImportVisible(false);
        }}
        footer={null}
        width={600}
        destroyOnClose
      >
        <Upload
          accept=".xlsx,.xls"
          beforeUpload={handleExcelUpload}
          showUploadList={false}
          disabled={importLoading}
        >
          <Button 
            type="primary" 
            icon={<UploadOutlined />}
            loading={importLoading}
            block
            size="large"
          >
            {importLoading ? '导入中...' : '选择Excel文件上传'}
          </Button>
        </Upload>
        
        <div style={{ marginTop: 16, padding: '12px', background: '#f5f5f5', borderRadius: '4px' }}>
          <Typography.Text type="secondary">
            <FileExcelOutlined style={{ marginRight: 4 }} />
            请上传包含项目信息的Excel文件
          </Typography.Text>
          <br />
          <Typography.Text type="secondary" style={{ fontSize: '12px', marginTop: 8, display: 'block' }}>
            支持的文件格式：.xlsx, .xls
          </Typography.Text>
        </div>
      </Modal>
    </>
  );
};

export default SubProjectTable;